from flask_restplus import Resource, Namespace, fields, marshal, reqparse
from common.decorators import catch_error
from common.responses import ok
from common.response_model import base_model, pagination_model
from common.request_parser import get_parser as base_get_parser
from app.user.decorators import token_required
from app.storage.warehouse.model import Warehouse
from app.storage.warehouse import dao

api = Namespace('warehouse')

# ---------- model ----------
warehouse_model = base_model.inherit('warehouse_model', {})
warehouse_paginate_model = pagination_model.inherit('warehouse_paginate_model', {
    "items": fields.Nested(warehouse_model)
})

# ---------- create parser ----------
create_parser = reqparse.RequestParser()
create_parser.add_argument('name', type=str, required=True, help='仓库名称')
create_parser.add_argument('short_name', type=str, help='名称拼音缩写，默认不用填写')
create_parser.add_argument('notes', type=str, help='备注')
create_parser.add_argument('is_active', type=bool, choices=[True, False], help='是否启用')

# ---------- get parser ----------
get_parser = base_get_parser.copy()
get_parser.add_argument('all', type=bool, default=False, help='是否获取全部')


class WarehousesResource(Resource):
    @catch_error
    @token_required
    @api.expect(create_parser)
    def post(self):
        """创建"""
        args = create_parser.parse_args()
        new_obj = Warehouse.create(**args, commit=True)
        return ok(data=marshal(new_obj, warehouse_model),
                  message='create success')

    @catch_error
    @token_required
    @api.expect(get_parser)
    def get(self):
        """获取列表"""
        args = get_parser.parse_args()
        if args.pop('all'):
            warehouses = Warehouse.query.filter_by_company_id(
                is_active=args.get('is_active')).all()
            return ok(data=marshal({"items": warehouses}, warehouse_paginate_model),
                      message='get success')

        pagination = dao.get_by_page(**args)
        return ok(data=marshal(pagination, warehouse_paginate_model),
                  message='get success')


# ---------- put parser ----------
put_parser = create_parser.copy()


class WarehouseResource(Resource):
    @catch_error
    @token_required
    def get(self, obj_id):
        """获取"""
        obj = Warehouse.query.filter_by(id=obj_id).first()
        return ok(data=marshal(obj, warehouse_model),
                  message='get success')

    @catch_error
    @token_required
    @api.expect(put_parser)
    def put(self, obj_id):
        """更新"""
        args = put_parser.parse_args()
        for key in list(args.keys()):
            if args.get(key) is None:
                del args[key]
        obj = Warehouse.query.filter_by(id=obj_id).first()
        obj.update(**args, commit=True)
        return ok(data=marshal(obj, warehouse_model),
                  message='update success')

    @catch_error
    @token_required
    def delete(self, obj_id):
        """获取"""
        obj = Warehouse.query.filter_by(id=obj_id).first()
        delete_id = obj.hard_delete(commit=True)
        return ok(
            data={
                'id': delete_id
            },
            message='delete success')


# --------- route ----------
api.add_resource(WarehousesResource, '/warehouses')
api.add_resource(WarehouseResource, '/warehouse/<int:obj_id>')

# 注册 response 文档
api.models[warehouse_model.name] = warehouse_model
